var utilsmd5 = require('../../utils/md5.js')
var app = getApp()
Page({
  data: {
    arraydetail: [],
    productsInfo: '',
    productsPayInfo: '',
    info: {},
    deliveryFee: 0,
    addressId: 0,
    myProduct: [],
    buttonconfirm: false,
    buttonbuy: true,
    selectall: false,
    paybase: 0,
    payall: 0,
    farmId: 0,
    aDelivery: [],
    aAddress: [],
    deliveryType: 1,
    haveDeliveryType: 0,
    userNote: '',
    author: 'Lotus'
  },
  buy: function () {
    var that = this;
    console.log("buy start");
    var service = 'Order.payForProducts';
    var addressId = that.data.addressId;
    var payType = 0;
    var otherType = 'wxcxjsapipay';
    var otherFee = that.data.payall;
    var productsInfo = that.data.productsPayInfo;

    console.log("openId:" + app.globalData.openId);
    console.log("addressId:" + addressId);
    console.log("payType:" + payType);
    console.log("productsInfo:" + productsInfo);
    console.log("otherType:" + otherType);
    console.log("otherFee:" + otherFee);
    /**/
    wx.request({
      method: 'POST',
      url: app.globalData.APIURL,
      data: { service: service, openId: app.globalData.openId, addressId: addressId, payType: payType, productsInfo: productsInfo, otherType: otherType, otherFee: otherFee },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: function (res) {

        console.log("success:" + res.data.data);

        if (!res.data.data.code) {
          var info = res.data.data.info.tradeNo;
          var param = [];
          param['appid'] = info.appId;
          param['timeStamp'] = info.timeStamp;
          param['nonceStr'] = info.nonceStr;
          param['package'] = info.package;
          param['paySign'] = info.sign;

          // param['prepayid'] = info.prepayid; 
          // param['partnerid'] = info.partnerid;
          that.pay(param);
        } else {
          wx.showToast({
            title: res.data.data.message,
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.log("fail:" + res);
      },
    })
    console.log("buy end");
  },

  pay: function (param) {
    var that = this;
    console.log("支付 start");
    console.log(param)
    var appid = app.globalData.APPID;
    var timeStamp = '' + param.timeStamp;
    var nonceStr = param.nonceStr;
    var pkg = param.package;
    var signType = 'MD5';
    //var key = app.globalData.KEY;
    //var paySign = utilsmd5.hexMD5('appId=' + appid + '&nonceStr=' + nonceStr + '&package=' + pkg + '&signType=' + signType + '&timeStamp=' + timeStamp + '&key=' + key).toUpperCase();
    var paySign = param.paySign;
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: pkg,
      signType: signType,
      paySign: paySign,
      success: function (res) {
        // success
        console.log("支付")
        //console.log(res)
         wx.redirectTo({
            url: 'orderlist'
          })
      },
      complete: function () {
        // complete

        that.setData({
          buttonconfirm: true,
          buttonbuy: false
        })
        wx.redirectTo({
          url: 'orderlist'
        })
      }
    })
    console.log("支付 end");
  },
  getinfo: function () {
    var that = this;
    var service = 'Order.getDeliveryAndCouponInfo';
    var productsInfo = that.data.productsInfo;

    wx.request({
      method: 'POST',
      url: app.globalData.APIURL,
      data: { service: service, openId: app.globalData.openId, productsInfo: productsInfo },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        console.log("success:" + res.data.data);

        if (!res.data.data.code) {
          var info = res.data.data.info;
          var payall = (parseFloat(that.data.paybase) + parseFloat(that.data.deliveryFee)).toFixed(2);
          var farmId = that.data.farmId;
          var aDelivery = [];
          for (var i in info) {
            if (i == farmId) {
              aDelivery = info[i].delivery;
            }
          }
          that.setData({
            haveDeliveryType: 1,
            aDelivery: aDelivery,
            payall: payall,
            buttonconfirm: false,
            buttonbuy: true
          })
        }


      },
      fail: function (res) {
        console.log("fail:" + res);
      },
    })
  },
  setinfo: function () {

    var that = this;
    var farmId = that.data.farmId;
    var products = that.data.arraydetail;
    var myProduct = that.data.myProduct;
    var deliveryType = that.data.deliveryType;
    var deliveryFee = that.data.deliveryFee;
    var userNote = that.data.userNote;
    var no = 0;
    var paybase = 0;

    var productsInfo = '{"' + farmId + '":[';
    var productsPayInfo = '{"' + farmId + '":{"couponId":0,"deliveryType":"' + deliveryType + '","deliveryFee":"' + deliveryFee + '","userNote":"' + userNote + '","items":[';
    for (var i in products) {
      if (myProduct[products[i].productId]) {
        if (no > 0) {
          productsInfo += ',';
          productsPayInfo += ',';
        }
        productsInfo += '{"productId":' + products[i].productId + ',"buyAmount":' + products[i].productAmount + '}';
        productsPayInfo += '{"productId":' + products[i].productId + ',"buyAmount":' + products[i].productAmount + '}';
        paybase += products[i].productAmount * products[i].productPrice;
        no++;
      }
    }
    productsInfo += ']}';
    productsPayInfo += ']}}';

    that.setData({ productsPayInfo: productsPayInfo, productsInfo: productsInfo, paybase: paybase, buttonconfirm: true, buttonbuy: false });
     that.getinfo();
  },
  getlist: function () {

    var that = this;
    var service = 'ShoppingCart.get';
    var openId = app.globalData.openId;
    wx.request({
      method: 'POST',
      url: app.globalData.APIURL,
      data: { service: service, openId: app.globalData.openId },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        //console.log("success:" + res.data.data.code);

        if (!res.data.data.code) {
          var list = res.data.data.list;
          var products = res.data.data.list[0].products;
          var farmId = res.data.data.list[0].farmId;
          that.setData({
            arraydetail: res.data.data.list[0].products,
            farmId: farmId
          })
        }
        if (res.data.data.code=='1') {
          that.setData({
            arraydetail: []
          })
        }
        that.setinfo();
      },
      fail: function (res) {
        console.log("fail:" + res);
      },
    })
     
  },
  getAddress: function () {
    var that = this;
    var service = 'ReceiptAddress.get';
    wx.request({
      method: 'POST',
      url: app.globalData.APIURL,
      data: { service: service, openId: app.globalData.openId },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        //console.log("success:" + res.data.data);
        var aAddress = res.data.data.list;
        if (!res.data.data.code) {
          that.setData({
            aAddress: aAddress
          })
        }
        for (var i in aAddress) {
          if (aAddress[i].isDefault == '1') {
            //console.log("addressId:" + aAddress[i].addressId);
            that.setData({ addressId: aAddress[i].addressId })
          }
        }
      },
      fail: function (res) {
        //console.log("fail:" + res);
      },
    })
  },
  changeAddress: function (e) {
    this.setData({ addressId: e.detail.value })
  },
  changeUserNote: function (e) {
    this.setData({ userNote: e.detail.value })
  },
  changeDeliveryType: function (e) {
    var that = this;
    var deliveryType = e.detail.value;
    var aDelivery = that.data.aDelivery;
    var deliveryFee = 0;
    for (var i in aDelivery) {
      if (aDelivery[i].type == deliveryType) {
        deliveryFee = aDelivery[i].fee;
        if (!deliveryFee) {
          deliveryFee = 0;
        }
      }
    }
    var payall = (parseFloat(that.data.paybase) + parseFloat(deliveryFee)).toFixed(2);
    that.setData({ deliveryType: deliveryType, deliveryFee: deliveryFee, payall: payall });

  },

  buyproduct: function (productId) {
    var that = this;
    var myProduct =[];
    myProduct[productId] = true;
    that.setData({ myProduct: myProduct });
    that.getlist();  
  },
  onLoad: function (options) {
    var that = this;
    if (options.fromInviteCode) {
      app.globalData.fromInviteCode=options.fromInviteCode;
    }
    app.appstart();
    var productId=0;
    if (options.productId) {
      var productId=options.productId;
    }   
    that.getAddress();
    that.buyproduct(productId);
  }
})